# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=ruby-pg_query
_gemname=pg_query
# Keep in mind the aport libpg_query when bumping.
pkgver=4.2.3
pkgrel=2
pkgdesc="PostgreSQL query parsing and normalization library for Ruby"
url="https://github.com/pganalyze/pg_query"
# x86, armhf, armv7: fingerprint feature is broken on 32-bit
# s390x: Failing tests
# riscv64 blocked by libpg_query
arch="all !x86 !armhf !armv7 !s390x !riscv64"
license="BSD-3-Clause"
depends="ruby ruby-google-protobuf>=3.15.5"
checkdepends="ruby-rspec"
makedepends="
	libpg_query-dev
	postgresql15-dev
	protoc
	ruby-dev
	xxhash-dev
	"
source="https://github.com/pganalyze/pg_query/archive/v$pkgver/$pkgname-$pkgver.tar.gz
	unbundle-deps.patch
	"
builddir="$srcdir/$_gemname-$pkgver"

prepare() {
	default_prepare

	# Remove bundled dependencies.
	cd ext/pg_query
	rm protobuf-c.c xxhash.c src_*.c src_*.h
	find . -name 'pg_query*' ! -name 'pg_query_ruby.*' -delete
	rm -Rf include
}

build() {
	# Regenerate Ruby source from pg_query.proto provided by libpg_query
	# package - to be sure that we use correct version.
	protoc --proto_path=/usr/include/pg_query \
		--ruby_out=lib/pg_query \
		/usr/include/pg_query/pg_query.proto

	gem build $_gemname.gemspec

	CFLAGS="$CFLAGS -I$(pg_config --includedir-server)" \
	gem install \
		--local \
		--install-dir dist \
		--ignore-dependencies \
		--no-document \
		--verbose \
		$_gemname

	# Needed for running tests.
	cp -l dist/extensions/*/*/$_gemname-*/$_gemname/*.so lib/$_gemname/
}

check() {
	rspec --format d
}

package() {
	local gemdir="$pkgdir/$(ruby -e 'puts Gem.default_dir')"
	cd "$builddir"/dist

	mkdir -p "$gemdir"
	cp -r extensions gems specifications "$gemdir"/

	# Remove unnecessary and duplicated files.
	rm -f "$gemdir"/extensions/*/*/$_gemname-*/mkmf.log
	cd "$gemdir"/gems/$_gemname-$pkgver
	rm -rf ext/ lib/$_gemname/*.so LICENSE Rakefile *.md
}

sha512sums="
0d3794a3fe11abfe109bf73d25b5904983a174442687c101f33de01d29551a3bb7b00cdcd18ef45cb72e2740f4c8d21f58c57d58af54950a8a7b9d6f35ed71c3  ruby-pg_query-4.2.3.tar.gz
b2cccd6667a1ad6e98346d54f7f3a441a9cc472892cb8ace026d4849072824a70d0a1a81e9f57b373d9d28f05109836486247348b93ad4de0071700d85cc5ab7  unbundle-deps.patch
"
